<template>
  <el-dialog
    :visible.sync="dialog"
    :close-on-click-modal="false"
    :title="title"
    width="500px"
    top="5px"
    @close="doClose"
  >
    <el-container>
      <div>
        <el-form ref="editForm" :model="phase" :rules="rules" label-width="auto" size="mini">
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="主题:" :required="!disabled" prop="scheduleSubject">
                <el-input v-model="phase.scheduleSubject" type="textarea" rows="1" size="mini" placeholder="请输入" :disabled="disabled" style="width: 300px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="开始日期:" :required="!disabled" prop="effDate">
                <el-date-picker v-model="phase.effDate" size="mini" type="date" format="MM/dd/yyyy" placeholder="选择日期" :disabled="disabled" :picker-options="effectiveDatePicker" style="width: 300px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="结束日期:" :required="!disabled" prop="operationEndDate">
                <el-date-picker v-model="phase.operationEndDate" size="mini" type="date" format="MM/dd/yyyy" placeholder="选择日期" :picker-options="expirationDatePicker" :disabled="disabled" style="width: 300px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="档期分类:" :required="!disabled" prop="scheduleGroup">
                <el-radio-group v-model="phase.scheduleGroup" :disabled="disabled">
                  <el-radio v-for="item in getSelector().scheduleGroups" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="部类:" :required="!disabled" prop="scheduleType">
                <el-radio-group v-model="phase.scheduleType" :disabled="disabled" @change="scheduleTypeChange">
                  <el-radio v-for="item in getSelector().scheduleTypes" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="品类:" prop="cateScope">
                <el-popover placement="top" width="300" trigger="hover">
                  <el-input v-model="filterText" placeholder="输入部门搜索" style="width: 275px;" clearable />
                  <!--<el-button type="text" size="mini" @click="unSelectAll">反选</el-button>
                  <el-button type="text" size="mini" @click="selectAll">全选</el-button>-->
                  <div style="height: 200px;width:300px;overflow:auto">
                    <el-tree
                      ref="categoryTree"
                      :data="categorys"
                      style="width:275px;"
                      show-checkbox
                      node-key="id"
                      highlight-current
                      :filter-node-method="filterNode"
                      :props="defaultProps"
                      :default-checked-keys="selectedCategorys"
                      @check="method.treeNodeCheck"
                    />
                  </div>
                  <el-input slot="reference" v-model="phase.cateScope" type="textarea" :disabled="disabled" rows="2" size="mini" placeholder="选择品类" readonly style="width: 300px;" />
                </el-popover>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="渠道:" prop="channel">
                <el-checkbox-group v-model="channels" disabled>
                  <el-checkbox v-for="item in getSelector().channels" :key="item.value" :label="item.value">{{ item.name }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item size="mini" label="业态:" prop="storeType">
                <el-radio-group v-model="phase.storeType" disabled>
                  <el-radio v-for="item in getSelector().storeTypes" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-container>
    <el-row v-if="showSaveButton" :gutter="20" style="margin-top:30px;">
      <template v-if="showPublicButton">
        <el-col :span="10">
          <div style="text-align: right;"><el-button type="primary" round size="small" @click="doPublish()">发布</el-button></div>
        </el-col>
        <el-col :span="4"><div style="text-align: right;"><el-button type="primary" round size="small" @click="doSave()">保存</el-button></div></el-col>
        <el-col :span="1"><div><el-button type="primary" size="small" round @click="doClose()">取消</el-button></div></el-col>
      </template>
      <template v-else>
        <el-col :span="12"><div style="text-align: right;"><el-button type="primary" round size="small" @click="doSave()">保存</el-button></div></el-col>
        <el-col :span="1"><div><el-button type="primary" size="small" round @click="doClose()">取消</el-button></div></el-col>
      </template>
    </el-row>
  </el-dialog>
</template>
<script>
import { Message } from 'element-ui'
import { parseToString } from '@/utils/datefromat'
import { getSelector, emptySchedule } from './js/edit'
import { showNameByValue } from '@/utils/selectUtil'
import { add, update, publish } from '@/api/olm/schedule'
import { findDeptCategory } from '@/api/olm/category'
import Rule from './js/rules'
import Method from './js/methods'
import Validate from './js/validates'

export default {
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      loading: false,
      currentObj: this,
      activeName: 'edit',
      rule: new Rule(this),
      method: new Method(this),
      validate: new Validate(this),
      title: '新增档期',
      rules: {},
      phase: this.emptySchedule(),
      defaultProps: {
        children: 'categorys',
        label: 'label'
      },
      categorys: null,
      allCategorys: [],
      freshCategorys: [],
      nonFreshCategorys: [],
      filterText: '',
      selectedCategorys: [],
      effectiveDatePicker: {
        disabledDate: (time) => {
          var current = new Date()
          current.setDate(current.getDate() + 1)
          current.setHours(0)
          current.setMinutes(0)
          current.setSeconds(0)
          current.setMilliseconds(0)
          return time.getTime() < current.getTime()
        }
      },
      expirationDatePicker: {
        disabledDate: (time) => {
          if (this.phase.operationEndDate) {
            var effectiveDate = new Date(this.phase.operationEndDate)
            effectiveDate.setDate(effectiveDate.getDate())
            effectiveDate.setHours(0)
            effectiveDate.setMinutes(0)
            effectiveDate.setSeconds(0)
            effectiveDate.setMilliseconds(0)
            return time.getTime() < effectiveDate.getTime()
          } else {
            var current = new Date()
            current.setHours(0)
            current.setMinutes(0)
            current.setSeconds(0)
            current.setMilliseconds(0)
            return time.getTime() < current.getTime()
          }
        }
      }
    }
  },
  computed: {
    showSaveButton: function() {
      return !this.phase.dataStatus || this.phase.dataStatus === 0 || this.phase.dataStatus === 1
    },
    showPublicButton: function() {
      return !this.phase.dataStatus || this.phase.dataStatus === 0
    },
    disabled: function() {
      return this.phase.dataStatus !== undefined && this.phase.dataStatus !== null && this.phase.dataStatus !== 0 && this.phase.dataStatus !== 1
    },
    channels: {
      get() {
        // console.log('get channels:' + this.phase.channel)
        var channels = []
        if (this.phase.channel !== null && this.phase.channel !== '') {
          channels = JSON.parse('[' + this.phase.channel + ']')
        }
        return channels
      },
      set(val) {
        // console.log('set channels:' + val)
        if (val !== null && val !== '') {
          this.phase.channel = val.join(',')
        } else {
          this.phase.channel = val
        }
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
    this.$nextTick(() => {
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.rule.initRules()
      this.loadTreeData()
    })
  },
  methods: {
    getSelector,
    emptySchedule,
    showNameByValue,
    parseToString,
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.id.slice(0, 2) === value
    },
    selectAll() {
      this.$refs.categoryTree.setCheckedNodes(this.categorys)
      this.method.setCateScope()
    },
    unSelectAll() {
      this.$refs.categoryTree.setCheckedNodes([])
      this.phase.cateScope = null
      this.selectedCategorys = []
    },
    setCategorys(val) {
      if (val === 1) {
        this.categorys = this.allCategorys
      } else if (val === 2) {
        this.categorys = this.freshCategorys
      } else if (val === 3) {
        this.categorys = this.nonFreshCategorys
      } else {
        this.categorys = this.allCategorys
      }
      this.method.setCateScope2(this.categorys)
      console.log('setCategorys')
      this.setSelectedTreeNodes()
    },
    scheduleTypeChange(val) {
      this.unSelectAll()
      this.setCategorys(val)
    },
    loadTreeData() {
      var _this = this
      findDeptCategory().then(res => {
        if (res) {
          _this.categorys = res
          _this.allCategorys = res
          _this.nonFreshCategorys.splice(0, _this.nonFreshCategorys.length)
          _this.freshCategorys.splice(0, _this.freshCategorys.length)
          _this.categorys.forEach(item => {
            if (item.isFresh) {
              _this.freshCategorys.push(item) // 鲜食
            } else {
              _this.nonFreshCategorys.push(item) // 非鲜食
            }
          })
        }
      })
    },
    setSelectedTreeNodes() {
      this.selectedCategorys = []
      if (this.phase.cateScope) {
        var cates = this.phase.cateScope.split(' ')
        if (cates) {
          cates.forEach(item => {
            if (item) {
              this.selectedCategorys.push(item.replace('/', ''))
            }
          })
        }
      }
    },
    // 关闭
    doClose() {
      this.dialog = false
      this.phase = this.emptySchedule()
      this.selectedCategorys = []
      this.unSelectAll()
      this.$refs.editForm.resetFields()
      // this.parent.toQuery()
    },
    // 保存
    doSave() {
      var _this = this
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.loading = true
            if (!this.phase.id) { // 新增
              add(this.phase).then(res => {
                Message({
                  message: '保存成功',
                  type: 'success',
                  duration: 2 * 1000
                })
                _this.doClose()
                _this.parent.toQuery()
                this.loading = false
              }, error => {
                console.log(error)
                this.loading = false
              })
            } else { // 修改
              update(this.phase).then(res => {
                Message({
                  message: '修改成功',
                  type: 'success',
                  duration: 2 * 1000
                })
                _this.doClose()
                _this.parent.toQuery()
                this.loading = false
              }, (error) => {
                console.log(error)
                this.loading = false
              })
            }
          })
        } else {
          Message({
            message: '校验失败',
            type: 'warning',
            duration: 2 * 1000
          })
        }
      })
    },
    doPublish() { // 发布
      var _this = this
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认发布？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.loading = true
            publish(this.phase).then(res => {
              Message({
                message: '发布成功',
                type: 'success',
                duration: 2 * 1000
              })
              _this.doClose()
              _this.parent.toQuery()
              this.loading = false
            }, error => {
              console.log(error)
              this.loading = false
            })
          })
        } else {
          Message({
            message: '校验失败',
            type: 'warning',
            duration: 2 * 1000
          })
        }
      })
    }
  }
}
</script>
<style>
</style>
